'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { RefreshCw, Eye, EyeOff, Database, Key, Users } from 'lucide-react'

export function AdminDebugPanel() {
  const [debugInfo, setDebugInfo] = useState<any>(null)
  const [showTokens, setShowTokens] = useState(false)
  const [loading, setLoading] = useState(false)
  const [testResults, setTestResults] = useState<any>({})

  const collectDebugInfo = () => {
    const info = {
      environment: process.env.NODE_ENV,
      timestamp: new Date().toISOString(),
      localStorage: {},
      authStatus: {},
      apiEndpoints: {}
    }

    // 检查localStorage
    if (typeof window !== 'undefined') {
      info.localStorage = {
        // 统一使用auth-token，不再使用admin_token
        auth_token: localStorage.getItem('auth-token') ? '存在' : '不存在',
        admin_user: localStorage.getItem('admin_user') ? '存在' : '不存在'
      }

      // 解析用户信息
      try {
        const userStr = localStorage.getItem('admin_user')
        if (userStr) {
          const user = JSON.parse(userStr)
          info.authStatus = {
            isLoggedIn: true,
            userId: user.id,
            email: user.email,
            name: user.name,
            role: user.role
          }
        } else {
          info.authStatus = { isLoggedIn: false }
        }
      } catch (error) {
        info.authStatus = { error: '用户信息解析失败' }
      }
    }

    setDebugInfo(info)
  }

  const testApiEndpoint = async (endpoint: string, name: string) => {
    try {
      setTestResults(prev => ({ ...prev, [name]: { loading: true } }))

      // 统一使用auth-token，不再使用admin_token
      const token = localStorage.getItem('auth-token')
      const headers: any = { 'Content-Type': 'application/json' }
      
      if (token) {
        headers['Authorization'] = `Bearer ${token}`
      }

      const response = await fetch(endpoint, { headers })
      const data = await response.json()

      setTestResults(prev => ({
        ...prev,
        [name]: {
          loading: false,
          success: response.ok,
          status: response.status,
          data: data,
          error: response.ok ? null : data.error || '请求失败'
        }
      }))
    } catch (error) {
      setTestResults(prev => ({
        ...prev,
        [name]: {
          loading: false,
          success: false,
          error: error instanceof Error ? error.message : '网络错误'
        }
      }))
    }
  }

  const runAllTests = async () => {
    setLoading(true)
    setTestResults({})

    const tests = [
      { endpoint: '/api/auth/verify', name: '认证验证' },
      { endpoint: '/api/admin/tools', name: '工具列表' },
      { endpoint: '/api/admin/users', name: '用户列表' },
      { endpoint: '/api/tools', name: '公开工具' }
    ]

    for (const test of tests) {
      await testApiEndpoint(test.endpoint, test.name)
    }

    setLoading(false)
  }

  useEffect(() => {
    collectDebugInfo()
  }, [])

  const getTokenDisplay = (token: string | null) => {
    if (!token) return '无'
    if (!showTokens) return '***隐藏***'
    return token.length > 50 ? `${token.substring(0, 20)}...${token.substring(token.length - 10)}` : token
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Database className="w-5 h-5" />
            管理后台调试面板
          </CardTitle>
          <CardDescription>
            诊断认证状态和数据获取问题
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex gap-2">
            <Button onClick={collectDebugInfo} variant="outline" size="sm">
              <RefreshCw className="w-4 h-4 mr-2" />
              刷新信息
            </Button>
            <Button onClick={runAllTests} disabled={loading} size="sm">
              <Users className="w-4 h-4 mr-2" />
              {loading ? '测试中...' : '测试API'}
            </Button>
            <Button
              onClick={() => setShowTokens(!showTokens)}
              variant="outline"
              size="sm"
            >
              {showTokens ? <EyeOff className="w-4 h-4 mr-2" /> : <Eye className="w-4 h-4 mr-2" />}
              {showTokens ? '隐藏' : '显示'}令牌
            </Button>
          </div>

          {debugInfo && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* 环境信息 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm">环境信息</CardTitle>
                </CardHeader>
                <CardContent className="text-sm space-y-2">
                  <div>环境: <span className="font-mono">{debugInfo.environment}</span></div>
                  <div>时间: <span className="font-mono">{debugInfo.timestamp}</span></div>
                </CardContent>
              </Card>

              {/* 认证状态 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm">认证状态</CardTitle>
                </CardHeader>
                <CardContent className="text-sm space-y-2">
                  <div>登录状态: <span className={`font-mono ${debugInfo.authStatus.isLoggedIn ? 'text-green-600' : 'text-red-600'}`}>
                    {debugInfo.authStatus.isLoggedIn ? '已登录' : '未登录'}
                  </span></div>
                  {debugInfo.authStatus.isLoggedIn && (
                    <>
                      <div>用户: <span className="font-mono">{debugInfo.authStatus.name}</span></div>
                      <div>邮箱: <span className="font-mono">{debugInfo.authStatus.email}</span></div>
                      <div>角色: <span className="font-mono">{debugInfo.authStatus.role}</span></div>
                    </>
                  )}
                </CardContent>
              </Card>

              {/* 存储状态 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm flex items-center gap-2">
                    <Key className="w-4 h-4" />
                    本地存储
                  </CardTitle>
                </CardHeader>
                <CardContent className="text-sm space-y-2">
                  <div>认证令牌: <span className="font-mono">{debugInfo.localStorage.auth_token}</span></div>
                  <div>管理员用户: <span className="font-mono">{debugInfo.localStorage.admin_user}</span></div>
                  {showTokens && (
                    <div className="mt-2 p-2 bg-gray-100 rounded text-xs">
                      <div>令牌内容: {getTokenDisplay(localStorage.getItem('auth-token'))}</div>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* API测试结果 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm">API测试结果</CardTitle>
                </CardHeader>
                <CardContent className="text-sm space-y-2">
                  {Object.keys(testResults).length === 0 ? (
                    <div className="text-gray-500">点击"测试API"开始测试</div>
                  ) : (
                    Object.entries(testResults).map(([name, result]: [string, any]) => (
                      <div key={name} className="flex items-center justify-between">
                        <span>{name}:</span>
                        <span className={`font-mono ${result.loading ? 'text-yellow-600' : result.success ? 'text-green-600' : 'text-red-600'}`}>
                          {result.loading ? '测试中...' : result.success ? `✅ ${result.status}` : `❌ ${result.status || 'ERROR'}`}
                        </span>
                      </div>
                    ))
                  )}
                </CardContent>
              </Card>
            </div>
          )}

          {/* 错误详情 */}
          {Object.values(testResults).some((result: any) => result.error) && (
            <Alert variant="destructive">
              <AlertDescription>
                <div className="space-y-2">
                  <div className="font-semibold">API错误详情:</div>
                  {Object.entries(testResults)
                    .filter(([_, result]: [string, any]) => result.error)
                    .map(([name, result]: [string, any]) => (
                      <div key={name} className="text-sm">
                        <strong>{name}:</strong> {result.error}
                      </div>
                    ))}
                </div>
              </AlertDescription>
            </Alert>
          )}

          {/* 成功的数据预览 */}
          {Object.values(testResults).some((result: any) => result.success && result.data) && (
            <Card>
              <CardHeader>
                <CardTitle className="text-sm">数据预览</CardTitle>
              </CardHeader>
              <CardContent>
                {Object.entries(testResults)
                  .filter(([_, result]: [string, any]) => result.success && result.data)
                  .map(([name, result]: [string, any]) => (
                    <div key={name} className="mb-4">
                      <div className="font-semibold text-sm mb-2">{name}:</div>
                      <pre className="text-xs bg-gray-100 p-2 rounded overflow-auto max-h-32">
                        {JSON.stringify(result.data, null, 2)}
                      </pre>
                    </div>
                  ))}
              </CardContent>
            </Card>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
